<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Console\Commands;

use App\Models\User;
use App\Models\UserPosition;
use App\Models\UserProfile;
use Illuminate\Console\Command;

class CensusUserPosition extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'census:user_position';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计用户的位置信息';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $userProfiles = UserProfile::query()->get();
        $users = User::query()->select('created_at', 'id')->get()->toArray();
        $userCreateTimeMap = array_column($users, null, 'id');
        /** @var UserProfile $userProfile */
        foreach ($userProfiles as $userProfile) {
            $userId = $userProfile->user_id;
            $createTime = $userCreateTimeMap[$userId]['created_at'] ?? $userProfile->created_at;
            // 从注册时间开始计算
            $createDay = explode(' ', $createTime)[0];
            $notInLocationDays = $this->calcUserNotInLocationDays($userId, $createDay);
            $userProfile->successive_not_in_village_days = $notInLocationDays;
            $userProfile->save();
        }
        return 0;
    }

    private function calcUserNotInLocationDays(int $userId, string $startDay)
    {
        $currTime = time();
        $userPositions = UserPosition::query()->where('user_id', $userId)->orderByDesc('id')->get();
        /** @var UserPosition $userPosition */
        foreach ($userPositions as $userPosition) {
            if (checkInLocation($userPosition->latitude, $userPosition->longitude)) {
                // 最近的一次在村内的时间
                return ceil(($currTime - $userPosition->report_time) / (24 * 3600));
            }
        }
        return ceil(($currTime - strtotime($startDay)) / (24 * 3600));
    }
}
